# -*- coding: utf-8 -*

from helper.readurl import readUrl
from xml.dom import minidom

from dictapi import *

class DictcnAPI(DictAPI):
    def __init__(self):
        super(DictcnAPI,self).__init__(r'Dict.cn')
        self.url_reader = readUrl(1)
        self.current_word = ''

    def translate(self,word):
        current_word = word
        page = self.url_reader.openUrl('http://dict.cn/ws.php?q=%s'%word)
        self.parse(page)

    def parse(self,xml_str):
        #utf_page = page.decode("gbk").encode("utf8").replace('GBK', 'utf-8');
        #utf_page = unicode(xml_str,"gbk").encode("utf-8")[38:]
        utf_page = unicode(xml_str,"gbk").encode("utf-8").replace('GBK', 'utf-8')
        dom = minidom.parseString(utf_page)
        root = dom.documentElement
        self.result.lookup_word = self.getTagText(root,'key')
        self.result.define = self.getTagText(root,'def')

    def getTagText(self, root, tag):  #xml Parse
        try:
            node = root.getElementsByTagName(tag)[0]
        except:
            return "no"
        rc = ""
        for node in node.childNodes:
            if node.nodeType in ( node.TEXT_NODE, \
                            node.CDATA_SECTION_NODE):
                rc = rc + node.data
        return rc


if __name__ == '__main__':
    dict = DictcnAPI()
    dict.translate('current')
